package top.mcwebsite.playandroid.business.home.impl.ui

import android.util.Log
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.unit.Velocity

enum class CollapsingState {
    EXPANDED,
    COLLAPSE,
}

@Composable
fun CollapsingLayout(
    modifier: Modifier,
    header: @Composable (CollapsingState) -> Unit,
    content: @Composable () -> Unit
) {
    BoxWithConstraints(
        modifier = modifier.fillMaxSize()
    ) {
        var collapsingState by remember {
            mutableStateOf(CollapsingState.EXPANDED)
        }
        // 采用嵌套滑动，标题栏和下方的内容进行联动
        val scrollConnection = remember {
            object : NestedScrollConnection {
                var scrollY = 0f
                var dragZeroCount = 0
                override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
                    scrollY += consumed.y
                    if (scrollY >= 30) {
                        collapsingState = CollapsingState.EXPANDED
                    } else if (scrollY <= -30) {
                        collapsingState = CollapsingState.COLLAPSE
                    }
                    if (consumed.y == 0f) {
                        dragZeroCount++
                        if (collapsingState == CollapsingState.COLLAPSE && dragZeroCount >= 30) {
                            collapsingState = CollapsingState.EXPANDED
                        }
                    }
                    return super.onPostScroll(consumed, available, source)
                }

                // 松开手指，惯性滑动
                override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
                    scrollY = 0f
                    dragZeroCount = 0
                    return super.onPostFling(consumed, available)
                }
            }
        }
        Column(
            modifier = Modifier
                .fillMaxSize()
                .nestedScroll(scrollConnection)
        ) {
            header(collapsingState)
            content()
        }
    }
}